package com.newdjk.newdoctor.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.AllFunctionAdapter;
import com.newdjk.newdoctor.adapter.SelectFunctionAdapter;
import com.newdjk.newdoctor.db.gen.LoginDataDao;
import com.newdjk.newdoctor.entity.AppLicationEntity;
import com.newdjk.newdoctor.entity.LoginData;
import com.newdjk.newdoctor.utils.AppLicationUtils;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 重置密码
 */
public class AllFunctionActivity extends BasActivity {


    private static final String TAG = "AllFunctionActivity";
    @BindView(R.id.selectRecyleview)
    RecyclerView selectRecyleview;
    @BindView(R.id.media_recycleview)
    RecyclerView mediaRecycleview;
    @BindView(R.id.yunying_recyleview)
    RecyclerView yunyingRecyleview;
    @BindView(R.id.learn_recyleview)
    RecyclerView learnRecyleview;
    @BindView(R.id.peizhi_recyleview)
    RecyclerView peizhiRecyleview;
    @BindView(R.id.tv_yaopian)
    TextView tvYaopian;
    @BindView(R.id.tv_yunying)
    TextView tvYunying;
    @BindView(R.id.tv_xuexi)
    TextView tvXuexi;
    @BindView(R.id.tv_peizhi)
    TextView tvPeizhi;
    private ItemTouchHelper mItemTouchHelper;


    private List<AppLicationEntity> selectlist = new ArrayList<>();
    private List<AppLicationEntity> yaopinlist = new ArrayList<>();
    private List<AppLicationEntity> yunyinglist = new ArrayList<>();
    private List<AppLicationEntity> learnlist = new ArrayList<>();
    private List<AppLicationEntity> peizhilist = new ArrayList<>();

    private List<AppLicationEntity> listAllFunction = new ArrayList<>();

    private SelectFunctionAdapter mSelectFunctionAdapter;
    private AllFunctionAdapter myaopinAdapter;
    private AllFunctionAdapter myunyingAdapter;
    private AllFunctionAdapter mlearnAdapter;
    private AllFunctionAdapter mpeizhiAdapter;

    @Override
    protected String setTitle() {
        setRightText("完成");
        return "定制桌面";
    }


    @Override
    protected int initViewResId() {
        return R.layout.activity_function;
    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }


    @Override
    protected void onRightTvClick(View v) {
        super.onRightTvClick(v);

        LoginDataDao daoSession = MyApplication.getDbSession().getLoginDataDao();
        //先存储
        LoginData loginData = new LoginData();
        loginData.setPhone(MyApplication.LoginEntity.getUser().getMobile());
        loginData.setType(MyApplication.LoginEntity.getUser().getDrType());
        loginData.setList(selectlist);
        daoSession.insertOrReplace(loginData);
        RxBus.get().post(Event.home_function_refresh, false);
        ToastUtil.setToast("保存成功");
        finish();

    }

    @Override
    protected void initListener() {
        mSelectFunctionAdapter.setOnEditListener(new SelectFunctionAdapter.OnItemEditedClickListener() {
            @Override
            public void OnItemEdited(int position) {
                if (selectlist.size() == 1) {
                    ToastUtil.setToast("最少留一个项目");
                    return;
                }
                String desc = selectlist.get(position).getAppDesc();
                selectlist.remove(position);
                mSelectFunctionAdapter.notifyDataSetChanged();
                updataAllFunction(desc);
            }
        });

        myaopinAdapter.setOnEditListener(new AllFunctionAdapter.OnItemEditedClickListener() {
            @Override
            public void OnItemEdited(int position) {
                if (selectlist.size() == 4) {
                    ToastUtil.setToast("最多添加四个项目");
                    return;
                }
                yaopinlist.get(position).setIsselect(true);
                selectlist.add(yaopinlist.get(position));
                myaopinAdapter.notifyDataSetChanged();
                mSelectFunctionAdapter.notifyDataSetChanged();

            }
        });
        myunyingAdapter.setOnEditListener(new AllFunctionAdapter.OnItemEditedClickListener() {
            @Override
            public void OnItemEdited(int position) {
                if (selectlist.size() == 4) {
                    ToastUtil.setToast("最多添加四个项目");
                    return;
                }
                yunyinglist.get(position).setIsselect(true);
                selectlist.add(yunyinglist.get(position));
                myunyingAdapter.notifyDataSetChanged();
                mSelectFunctionAdapter.notifyDataSetChanged();
            }
        });
        mlearnAdapter.setOnEditListener(new AllFunctionAdapter.OnItemEditedClickListener() {
            @Override
            public void OnItemEdited(int position) {
                if (selectlist.size() == 4) {
                    ToastUtil.setToast("最多添加四个项目");
                    return;
                }
                learnlist.get(position).setIsselect(true);
                selectlist.add(learnlist.get(position));
                mlearnAdapter.notifyDataSetChanged();
                mSelectFunctionAdapter.notifyDataSetChanged();

            }
        });
        mpeizhiAdapter.setOnEditListener(new AllFunctionAdapter.OnItemEditedClickListener() {
            @Override
            public void OnItemEdited(int position) {
                if (selectlist.size() == 4) {
                    ToastUtil.setToast("最多添加四个项目");
                    return;
                }
                peizhilist.get(position).setIsselect(true);
                selectlist.add(peizhilist.get(position));
                mpeizhiAdapter.notifyDataSetChanged();
                mSelectFunctionAdapter.notifyDataSetChanged();
            }
        });


    }

    private void updataAllFunction(String selectdesc) {
        for (int j = 0; j < yaopinlist.size(); j++) {
            if (selectdesc.equals(yaopinlist.get(j).getAppDesc())) {
                yaopinlist.get(j).setIsselect(false);
            }
        }
        for (int j = 0; j < yunyinglist.size(); j++) {
            if (selectdesc.equals(yunyinglist.get(j).getAppDesc())) {
                yunyinglist.get(j).setIsselect(false);
            }
        }
        for (int j = 0; j < learnlist.size(); j++) {
            if (selectdesc.equals(learnlist.get(j).getAppDesc())) {
                learnlist.get(j).setIsselect(false);
            }
        }
        for (int j = 0; j < peizhilist.size(); j++) {
            if (selectdesc.equals(peizhilist.get(j).getAppDesc())) {
                peizhilist.get(j).setIsselect(false);
            }
        }
        myaopinAdapter.notifyDataSetChanged();
        myunyingAdapter.notifyDataSetChanged();
        mlearnAdapter.notifyDataSetChanged();
        mpeizhiAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {
        queryDateFromDao();
        getAllFcuntion();

    }

    private void getAllFcuntion() {
        //刷新列表
        if (MyApplication.isLogin) {


            LoginDataDao daoSession = MyApplication.getDbSession().getLoginDataDao();

            List<LoginData> querylist = daoSession.queryBuilder().where(LoginDataDao.Properties.Phone.eq(MyApplication.LoginEntity.getUser().getMobile())).list();
            selectlist.clear();


            //如果有数据就用数据库中数据
            if (querylist.size() > 0) {
                selectlist.addAll(querylist.get(0).getList());
                mSelectFunctionAdapter.notifyDataSetChanged();

                //获取哪些选中哪些未选中
                editSelectOrUnselect();

            } else {
                //没有数据就使用默认数据
                listAllFunction.addAll(AppLicationUtils.getMedical());
                listAllFunction.addAll(AppLicationUtils.getOperate());
                listAllFunction.addAll(AppLicationUtils.getLearn());
                listAllFunction.addAll(AppLicationUtils.getConfigua());

                //然后取出来前面的  如果大于四个，就取出前面的四个
                if (listAllFunction.size() > 4) {
                    selectlist.addAll(listAllFunction.subList(0, 4));
                } else {//否则就全部添加进去
                    selectlist.addAll(listAllFunction);
                }
                mSelectFunctionAdapter.notifyDataSetChanged();

                //获取哪些选中哪些未选中
                editSelectOrUnselect();

            }
        }

    }

    private void editSelectOrUnselect() {

        yaopinlist.clear();
        yaopinlist.addAll(AppLicationUtils.getMedical());
        yunyinglist.clear();
        yunyinglist.addAll(AppLicationUtils.getOperate());
        learnlist.clear();
        learnlist.addAll(AppLicationUtils.getLearn());
        peizhilist.clear();
        peizhilist.addAll(AppLicationUtils.getConfigua());

        for (int i = 0; i < selectlist.size(); i++) {
            String selectdesc = selectlist.get(i).getAppDesc();
            for (int j = 0; j < yaopinlist.size(); j++) {
                if (selectdesc.equals(yaopinlist.get(j).getAppDesc())) {
                    yaopinlist.get(j).setIsselect(true);
                }
            }
            for (int j = 0; j < yunyinglist.size(); j++) {
                if (selectdesc.equals(yunyinglist.get(j).getAppDesc())) {
                    yunyinglist.get(j).setIsselect(true);
                }
            }
            for (int j = 0; j < learnlist.size(); j++) {
                if (selectdesc.equals(learnlist.get(j).getAppDesc())) {
                    learnlist.get(j).setIsselect(true);
                }
            }
            for (int j = 0; j < peizhilist.size(); j++) {
                if (selectdesc.equals(peizhilist.get(j).getAppDesc())) {
                    peizhilist.get(j).setIsselect(true);
                }
            }
        }
        if (yaopinlist.size() == 0) {
            tvYaopian.setVisibility(View.GONE);
            mediaRecycleview.setVisibility(View.GONE);
        } else {
            tvYaopian.setVisibility(View.VISIBLE);
            mediaRecycleview.setVisibility(View.VISIBLE);
        }


        if (yunyinglist.size() == 0) {
            tvYunying.setVisibility(View.GONE);
            yunyingRecyleview.setVisibility(View.GONE);
        } else {
            tvYunying.setVisibility(View.VISIBLE);
            yunyingRecyleview.setVisibility(View.VISIBLE);
        }

        if (learnlist.size() == 0) {
            tvXuexi.setVisibility(View.GONE);
            learnRecyleview.setVisibility(View.GONE);
        } else {
            tvXuexi.setVisibility(View.VISIBLE);
            learnRecyleview.setVisibility(View.VISIBLE);
        }
        if (peizhilist.size() == 0) {
            tvPeizhi.setVisibility(View.GONE);
            peizhiRecyleview.setVisibility(View.GONE);
        } else {
            tvPeizhi.setVisibility(View.VISIBLE);
            peizhiRecyleview.setVisibility(View.VISIBLE);
        }
        myaopinAdapter.notifyDataSetChanged();
        myunyingAdapter.notifyDataSetChanged();
        mlearnAdapter.notifyDataSetChanged();
        mpeizhiAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initView() {
        mSelectFunctionAdapter = new SelectFunctionAdapter(selectlist);
        GridLayoutManager mManagerLayout = new GridLayoutManager(MyApplication.getContext(), 4);
        selectRecyleview.setLayoutManager(mManagerLayout);
        selectRecyleview.setAdapter(mSelectFunctionAdapter);
        //拖拽处理
        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {

                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }

            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position

                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(selectlist, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(selectlist, i, i - 1);
                    }
                }
                Log.d(TAG, selectlist.toString());
                mSelectFunctionAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }

            @Override
            public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
//                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
//                    viewHolder.itemView.setBackgroundColor(getResources().getColor(R.color.lightgray));
//                }
            }

            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);
            }
        });
        mItemTouchHelper.attachToRecyclerView(selectRecyleview);


        myaopinAdapter = new AllFunctionAdapter(yaopinlist);
        GridLayoutManager myaopinLayout = new GridLayoutManager(MyApplication.getContext(), 4);
        mediaRecycleview.setLayoutManager(myaopinLayout);
        mediaRecycleview.setAdapter(myaopinAdapter);

        myunyingAdapter = new AllFunctionAdapter(yunyinglist);
        GridLayoutManager yunyingLayout = new GridLayoutManager(MyApplication.getContext(), 4);
        yunyingRecyleview.setLayoutManager(yunyingLayout);
        yunyingRecyleview.setAdapter(myunyingAdapter);

        mlearnAdapter = new AllFunctionAdapter(learnlist);
        GridLayoutManager learnLayout = new GridLayoutManager(MyApplication.getContext(), 4);
        learnRecyleview.setLayoutManager(learnLayout);
        learnRecyleview.setAdapter(mlearnAdapter);

        mpeizhiAdapter = new AllFunctionAdapter(peizhilist);
        GridLayoutManager mpeizhiLayout = new GridLayoutManager(MyApplication.getContext(), 4);
        peizhiRecyleview.setLayoutManager(mpeizhiLayout);
        peizhiRecyleview.setAdapter(mpeizhiAdapter);


    }

    private void queryDateFromDao() {
        //再取出来看看

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
